//
//  YLYBillPieViewController.m
//  iEasyBill
//
//  Created by student on 14-5-19.
//  Copyright (c) 2014年 com.yly16. All rights reserved.
//

#import "YLYBillPieViewController.h"
#import "Example2PieView.h"
#import "MyPieElement.h"
#import "PieLayer.h"
#import "XYPieChart.h"
#import "NQBarGraph.h"
#import "NQData.h"

@interface YLYBillPieViewController ()
{
    NSInteger year;
    NSInteger month;
}
@property (weak, nonatomic) IBOutlet UIView *centerView;
@property (weak, nonatomic) IBOutlet XYPieChart *pieChart;
@property (weak, nonatomic) IBOutlet NQBarGraph *barGraph;

@end

@implementation YLYBillPieViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    NSMutableArray * dataArray=[NSMutableArray array];
    NSDate * nowDate=[NSDate date];
    NQData * firstData=[NQData dataWithDate:nowDate andNumber:[NSNumber numberWithInt:3]];
    [dataArray addObject:firstData];
    for (int i=86400; i<8640000; i+=86400) {
        int rand=1+arc4random()%8;
        NQData * data=[NQData dataWithDate:[NSDate dateWithTimeInterval:i sinceDate:nowDate] andNumber:[NSNumber numberWithInt:rand]];
        [dataArray addObject:data];
    }
    
    self.barGraph.dataSource=dataArray;
    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    self.iPieList = [[NSMutableArray alloc]init];
    [self showCurrentMonth];
    self.iPieList = [self billPieByBillTypebyDate];
    self.centerView.layer.cornerRadius = self.centerView.bounds.size.height/2;
    self.centerView.layer.borderWidth = 5;
    
    
    [self.pieChart setDelegate:self];
    [self.pieChart setDataSource:self];
    [self.pieChart setShowPercentage:NO];
    
    float sum = 0;
    for (NSDictionary *dic in self.iPieList) {
        sum += [[dic objectForKey:@"money"] floatValue];
    }
    self.centerLabel.text = [NSString stringWithFormat:@"总计：\n￥%.2f",sum];
    if (self.iPieList.count != 0) {
        [self showPieInfoWithBillTypeNumberOfIndex:0];
    }
    _typeNumber = 0;
}
-(NSMutableArray *)billPieByBillTypebyDate{
    NSMutableArray *rootList = [[NSMutableArray alloc]init];
//    NSMutableArray *tempList = [[NSMutableArray alloc]init];
    //设置日期📅
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];           //设定时间格式,这里可以设置成自己需要的格式
    
    NSDate *Startdate =[dateFormat dateFromString:[NSString stringWithFormat:@"%d-0%d-01 00:00:00",year,month]];
    NSDate *Enddate =[dateFormat dateFromString:[NSString stringWithFormat:@"%d-0%d-30 00:00:00",year,month]];
    NSMutableArray *list = [[DatabaseManager shareManager]showBillByDate:Startdate toDate:Enddate toType:nil];
    NSMutableDictionary *dictionary;
    for (iBill *theBill in list) {
        dictionary = [[NSMutableDictionary alloc]init];
        if ( theBill.isPayOut.boolValue == YES) {
            
        }
        else{
            if (rootList.count == 0) {
                NSMutableArray *array = [[NSMutableArray alloc]init];
                [dictionary setObject:theBill.billTypeID forKey:@"type"];
                
                [dictionary setObject:theBill.billMoney forKey:@"money"];
                [array addObject:theBill];
                [dictionary setObject:array forKey:@"list"];
                
                [rootList addObject:dictionary];
            }
            else{
                BOOL isOk = NO;
                for (NSMutableDictionary *dic in rootList) {
                    if ([[dic objectForKey:@"type"] intValue] == theBill.billTypeID.intValue) {
                        NSMutableArray *array = [dic objectForKey:@"list"];
                        [array addObject:theBill];
                        float sum = [[dic objectForKey:@"money"] floatValue];
                        sum += theBill.billMoney.floatValue;
                        [dic setObject:[NSNumber numberWithFloat:sum] forKey:@"money"];
                        isOk = YES;
                        break;
                    }
                }
                if (isOk == NO) {
                    NSMutableArray *array = [[NSMutableArray alloc]init];
                    [dictionary setObject:theBill.billTypeID forKey:@"type"];
                    
                    [dictionary setObject:theBill.billMoney forKey:@"money"];
                    [array addObject:theBill];
                    [dictionary setObject:array forKey:@"list"];
                    
                    [rootList addObject:dictionary];
                }
            }
        }
        
    
    }
    
    
    return rootList;
}
-(NSInteger)showCurrentMonth{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
    NSInteger imonth;
    NSInteger iyear;
    NSInteger iday;
    
    imonth = [components month];
    iyear = [components year];
    iday = [components day];
    year = iyear;
    month = imonth;
    return imonth;
}
-(void)viewWillAppear:(BOOL)animated{
    self.iPieList = [self billPieByBillTypebyDate];
    float sum = 0;
    for (NSDictionary *dic in self.iPieList) {
        sum += [[dic objectForKey:@"money"] floatValue];
    }
    self.centerLabel.text = [NSString stringWithFormat:@"总计：\n￥%.2f",sum];
    if (self.iPieList.count != 0) {
        [self showPieInfoWithBillTypeNumberOfIndex:0];
    }
    _typeNumber = 0;
    [self.pieChart reloadData];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//随机变化颜色
- (UIColor*)randomColor
{
    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}
- (IBAction)topMonthPie:(id)sender {
    month --;
    if (month<1) {
        month = 12;
        year--;
    }
    self.iPieList = [self billPieByBillTypebyDate];
    [self.pieChart reloadData];
    float sum = 0;
    for (NSDictionary *dic in self.iPieList) {
        sum += [[dic objectForKey:@"money"] floatValue];
    }
    self.centerLabel.text = [NSString stringWithFormat:@"总计：\n￥%.2f",sum];
    self.title = [NSString stringWithFormat:@"%d年%d月",year,month];
    if (self.iPieList.count != 0) {
        [self showPieInfoWithBillTypeNumberOfIndex:0];
    }
    if (self.iPieList.count == 0){
        [self showPieInfoWithBillTypeNumberOfIndex:-20];
    }
}
- (IBAction)nextMonthPie:(id)sender {
    month ++;
    if (month>12) {
        month = 1;
        year++;
    }
    self.iPieList = [self billPieByBillTypebyDate];
    [self.pieChart reloadData];
    float sum = 0;
    for (NSDictionary *dic in self.iPieList) {
        sum += [[dic objectForKey:@"money"] floatValue];
    }
    self.centerLabel.text = [NSString stringWithFormat:@"总计：\n￥%.2f",sum];
    self.title = [NSString stringWithFormat:@"%d年%d月",year,month];
    if (self.iPieList.count != 0) {
        [self showPieInfoWithBillTypeNumberOfIndex:0];
    }
    if (self.iPieList.count == 0){
        [self showPieInfoWithBillTypeNumberOfIndex:-20];
    }
}
#pragma mark - XYPieChart Data Source

- (NSUInteger)numberOfSlicesInPieChart:(XYPieChart *)pieChart
{
    if (self.iPieList.count != 0) {
        return self.iPieList.count;
    }
    return 1;
}

- (CGFloat)pieChart:(XYPieChart *)pieChart valueForSliceAtIndex:(NSUInteger)index
{
    if (self.iPieList.count != 0) {
        NSDictionary *dic = [self.iPieList objectAtIndex:index];
        NSNumber *number = [NSNumber numberWithFloat:[[dic objectForKey:@"money"] floatValue]];
        return [number floatValue];
    }
    else{
        return 100.00;
    }
}

- (UIColor *)pieChart:(XYPieChart *)pieChart colorForSliceAtIndex:(NSUInteger)index
{
    return [self randomColor];
}

#pragma mark - XYPieChart Delegate
- (void)pieChart:(XYPieChart *)pieChart didSelectSliceAtIndex:(NSUInteger)index
{
    NSLog(@"did select slice at index %d",index);
    if (self.iPieList.count != 0) {
        [self showPieInfoWithBillTypeNumberOfIndex:index];
    }
    _typeNumber = index;
}
-(void)showPieInfoWithBillTypeNumberOfIndex:(int)index{
    float sum = 0;
    for (NSDictionary *dic in self.iPieList) {
        sum += [[dic objectForKey:@"money"] floatValue];
    }
    
    if (index >= 0) {
         float x = [[[self.iPieList objectAtIndex:index] objectForKey:@"money"] floatValue];
        sum = x/sum;
        
        NSDictionary *myDic = [self.iPieList objectAtIndex:index];
        iBillType *aType = [[DatabaseManager shareManager] showBillTypeByTypeID:[[myDic objectForKey:@"type"] integerValue]];
        self.showLabel.text = [NSString stringWithFormat:@"%@:%.2f％-￥%.2f",aType.typeName,sum*100.0,[[myDic objectForKey:@"money"] floatValue]];
        self.showImageView.image = [UIImage imageWithData:aType.typeImageData];
    }
    
    
    if (index < 0) {
        self.showLabel.text = [NSString stringWithFormat:@"无数据"];
        self.showImageView.image = nil;
    }
}

- (IBAction)showButton:(id)sender {
}
#pragma mark 传值
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    UIViewController *vc = [segue destinationViewController];
    if ([segue.identifier isEqualToString:@"pie2typeList"]) {
        if (self.iPieList.count != 0) {
            [vc setValue:self.iPieList[_typeNumber] forKey:@"rootDictionary"];
        }
    }else{
        
    }
}
@end
